using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.CostCenterServices;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.DeliveryOrderElseServices;
using MSIACCSL2.DeliveryTypeServices;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.ItemServices;
using MSIACCSL2.PalletServices;
using MSIACCSL2.SalesOrderServices;
using MSIACCSL2.SpkServices;
using MSIACCSL2.SubGroupServices;
using MSIACCSL2.Views.DeliveryOrderElse;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using DeleteDetailCompletedEventArgs = MSIACCSL2.DeliveryOrderElseServices.DeleteDetailCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.DeliveryOrderElseServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.DeliveryOrderElseServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.DeliveryOrderElseServices.SaveCompletedEventArgs;

namespace MSIACCSL2.ViewModels
{
    public class DeliveryOrderElseViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static Search frmSearch;
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private static NavigationService _NavigationService;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly CostCenterServicesClient CostCenterClient;


        private readonly CustomerServicesClient CustomerClient;
        private readonly DeliveryTypeServicesClient DeliveryTypeClient;
        private readonly InventoryServiceClient InventoryClient;
        private readonly ItemServicesClient ItemClient;
        private readonly PalletServicesClient PalletClient;
        private readonly SalesOrderServicesClient SalesOrderClient;
        private readonly SubGroupServiceClient SubgroupClient;
        private readonly DeliveryOrderElseServicesClient client;
        private readonly SpkServicesClient spkClient;
        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private WarehouseServicesClient WarehouseClient;
        private ObservableCollection<CostCenterDTO> _CostCenters;
        private ObservableCollection<CustomerDTO> _Customers;
        private DeliveryOrderElseDTO _DeliveryOrderElse;
        private PagedCollectionView _DeliveryOrderElses;
        private ObservableCollection<DeliveryTypeDTO> _DeliveryTypes;
        private string _Expression;
        private ObservableCollection<InventoryDTO> _Inventories;
        private bool _IsBusy;
        private bool _IsEnabled;
        private ObservableCollection<SalesOrderDTO> _SalesOrders;
        private ObservableCollection<SpkDTO> _Spks;
        private WarehouseDTO _WarehouseSelected;
        private List<string> _errors;
        private InventoryDTO _inventory;
        private ObservableCollection<ItemDTO> _items;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private ObservableCollection<PalletDTO> _pallets;
        private string _serialNumber;
        private ObservableCollection<SubGroupDTO> _subgroups;
        private ObservableCollection<WarehouseDTO> _warehouses;
        private Dictionary<string, object> criteria;
        private string expression;


        public DeliveryOrderElseViewModel()
        {
            IsEnabled = true;
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new DeliveryOrderElseServicesClient();
                CustomerClient = new CustomerServicesClient();
                DeliveryTypeClient = new DeliveryTypeServicesClient();
                SalesOrderClient = new SalesOrderServicesClient();
                InventoryClient = new InventoryServiceClient();
                ItemClient = new ItemServicesClient();
                SubgroupClient = new SubGroupServiceClient();
                WarehouseClient = new WarehouseServicesClient();
                PalletClient = new PalletServicesClient();
                CostCenterClient = new CostCenterServicesClient();
                spkClient = new SpkServicesClient();
                Errors = new List<string>();

                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveDeliveryOrderElse, CanSave);
                New = new DelegateCommand(NewDeliveryOrderElse, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchDeliveryOrderElse, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                LoadSOCommand = new DelegateCommand(LoadSalesOrder, CanLoadSOCommand);
                ApplicationService = new AplicationStateServicesClient();


                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    DeliveryOrderElse = new DeliveryOrderElseDTO();
                    DeliveryOrderElse.DODate = null;
                    GetDeliveryTypeList();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public ObservableCollection<CostCenterDTO> CostCenters
        {
            get { return _CostCenters; }
            private set
            {
                if (CostCenters == value) return;
                _CostCenters = value;
                FirePropertyChanged("CostCenters");
            }
        }

        public PagedCollectionView DeliveryOrderElses
        {
            get { return _DeliveryOrderElses; }

            private set
            {
                if (DeliveryOrderElses == value) return;
                _DeliveryOrderElses = value;
                int i = (CurrentPage*30);
                foreach (object DeliveryOrderElse in DeliveryOrderElses)
                {
                    i += 1;

                    ((DeliveryOrderElseDTO) DeliveryOrderElse).No = i;
                }
                FirePropertyChanged("DeliveryOrderElses");
                DeliveryOrderElses.CollectionChanged += DeliveryOrderElse_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<CustomerDTO> Customers
        {
            get { return _Customers; }
            private set
            {
                if (Customers == value) return;
                _Customers = value;
                FirePropertyChanged("Customers");
            }
        }


        public ObservableCollection<DeliveryTypeDTO> DeliveryTypes
        {
            get { return _DeliveryTypes; }
            private set
            {
                if (DeliveryTypes == value) return;
                _DeliveryTypes = value;
                FirePropertyChanged("DeliveryTypes");
            }
        }


        public ObservableCollection<SalesOrderDTO> SalesOrders
        {
            get { return _SalesOrders; }
            private set
            {
                if (SalesOrders == value) return;
                _SalesOrders = value;
                FirePropertyChanged("SalesOrders");
            }
        }

        public ObservableCollection<SpkDTO> Spks
        {
            get { return _Spks; }
            private set
            {
                if (Spks == value) return;
                _Spks = value;
                FirePropertyChanged("Spks");
            }
        }

        public ObservableCollection<InventoryDTO> InventorySearchs
        {
            get { return _Inventories; }
            private set
            {
                if (InventorySearchs == value) return;
                _Inventories = value;
                FirePropertyChanged("InventorySearchs");
            }
        }

        public String SerialNumber
        {
            get { return _serialNumber; }
            set
            {
                if (SerialNumber == value) return;
                _serialNumber = value;
                FirePropertyChanged("SerialNumber");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public ObservableCollection<ItemDTO> Items
        {
            get { return _items; }
            private set
            {
                if (Items == value) return;
                _items = value;
                FirePropertyChanged("Items");
            }
        }


        public ObservableCollection<PalletDTO> Pallets
        {
            get { return _pallets; }
            private set
            {
                if (Pallets == value) return;
                _pallets = value;
                FirePropertyChanged("Pallets");
            }
        }

        public ObservableCollection<SubGroupDTO> Subgroups
        {
            get { return _subgroups; }
            private set
            {
                if (Subgroups == value) return;
                _subgroups = value;
                FirePropertyChanged("Subgroups");
            }
        }

        public WarehouseDTO WarehouseSelected
        {
            get { return _WarehouseSelected; }
            set
            {
                if (WarehouseSelected == value) return;
                _WarehouseSelected = value;
                FirePropertyChanged("WarehouseSelected");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public DeliveryOrderElseDTO DeliveryOrderElse
        {
            get { return _DeliveryOrderElse; }
            private set
            {
                if (DeliveryOrderElse == value) return;
                _DeliveryOrderElse = value;
                FirePropertyChanged("DeliveryOrderElse");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public string this[string columnName]
        {
            get
            {
                if (validationHandler.BrokenRuleExists(columnName))
                {
                    return validationHandler[columnName];
                }
                return null;
            }
        }

        public string Expression
        {
            get { return _Expression; }
            set
            {
                if (Expression == value) return;
                _Expression = value;
                FirePropertyChanged("Expression");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public ICommand LoadSOCommand { get; set; }

        public ICommand LoadSPKCommand { get; set; }

        public InventoryDTO Inventory
        {
            get { return _inventory; }
            internal set
            {
                _inventory = value;
                FirePropertyChanged("Inventory");
            }
        }

        private void PrepareEdit()
        {
            GetDeliveryTypeList();
            DeliveryOrderElse = (DeliveryOrderElseDTO) Navigation.Args;
            GetSalesOrderList(DeliveryOrderElse.CostCenter);
            GetDeliveryOrderElse(DeliveryOrderElse.DONo);
            CekTransaksi();
        }


        private void PrepareAdd()
        {
            GetLastNoDeliveryOrderElse();
            GetDeliveryTypeList();
            DeliveryOrderElse = new DeliveryOrderElseDTO();
            DeliveryOrderElse.DeliveryOrderDetails = new ObservableCollection<DeliveryOrderElseDetailDTO>();
            CekTransaksi();
        }


        private void GetDeliveryOrderElse(string DONo)
        {
            client.GetDeliveryOrderElseCompleted += client_GetDeliveryOrderElseCompleted;
            client.GetDeliveryOrderElseAsync(DONo);
        }

        private void client_GetDeliveryOrderElseCompleted(object sender, GetDeliveryOrderElseCompletedEventArgs e)
        {
            client.GetDeliveryOrderElseCompleted += client_GetDeliveryOrderElseCompleted;
            DeliveryOrderElse = e.Result;
            //LoadWarehouse
            EventAggregator.PublishMessage("LoadWarehouseCompleted", e.Result);
            if (DeliveryOrderElse.DeliveryOrderDetails == null)
                DeliveryOrderElse.DeliveryOrderDetails = new ObservableCollection<DeliveryOrderElseDetailDTO>();
            if (DeliveryOrderElse.DeliveryOrderDetails.Count == 0)
                DeliveryOrderElse.DeliveryOrderDetails.Add(new DeliveryOrderElseDetailDTO());
        }

        private void GetCostCenterList()
        {
            CostCenterClient.GetAllCostCenterCompleted += CostCenterClient_GetAllCostCenterCompleted;
            CostCenterClient.GetAllCostCenterAsync();
        }

        private void CostCenterClient_GetAllCostCenterCompleted(object sender, GetAllCostCenterCompletedEventArgs e)
        {
            CostCenterClient.GetAllCostCenterCompleted -= CostCenterClient_GetAllCostCenterCompleted;
            CostCenters = e.Result;
        }

        public bool CanLoadSPK(Object param)
        {
            return true;
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void DeliveryOrderElse_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveDeliveryOrderElse(Object deliveryOrderElse)
        {
            //DeliveryOrderElse = (DeliveryOrderElseDTO) deliveryOrderElse;
            if (DeliveryOrderElse.DeliveryOrderDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (DeliveryOrderElse.DeliveryOrderDetails[0].Inventory == null)
                    DeliveryOrderElse.DeliveryOrderDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            DeliveryOrderElse.created_by = GlobalVar.User.UserID;
            DeliveryOrderElse.modified_by = GlobalVar.User.UserID;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(DeliveryOrderElse, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/DeliveryOrderElse/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                MessageBox.Show(e.err);
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            DeliveryOrderElses = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewDeliveryOrderElse(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/DeliveryOrderElse/frmAdd", UriKind.Relative));
        }


        private void SearchDeliveryOrderElse(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in DeliveryOrderElse.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(DeliveryOrderElse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(DeliveryOrderElse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(DeliveryOrderElse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(DeliveryOrderElse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(DeliveryOrderElse, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(DeliveryOrderElse, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(DeliveryOrderElse, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (
                        PropertyInfo propertyInfo in prop.GetValue(DeliveryOrderElse, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(DeliveryOrderElse, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(DeliveryOrderElse, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            DeliveryOrderElseSearch(criteria, expression,1);
        }

        private void DeliveryOrderElseSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression,page,criteria);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            DeliveryOrderElses = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
            criteria = (Dictionary<String, Object>)e.UserState;
        }


        private void GetDeliveryTypeList()
        {
            DeliveryTypeClient.GetAllDeliveryTypeCompleted += DeliveryTypeClient_GetAllDeliveryTypeCompleted;
            DeliveryTypeClient.GetAllDeliveryTypeAsync();
        }

        private void DeliveryTypeClient_GetAllDeliveryTypeCompleted(object sender,
                                                                    GetAllDeliveryTypeCompletedEventArgs e)
        {
            DeliveryTypeClient.GetAllDeliveryTypeCompleted -= DeliveryTypeClient_GetAllDeliveryTypeCompleted;
            DeliveryTypes = e.Result;

            if (DeliveryOrderElse != null)
            {
                if (DeliveryOrderElse.DeliveryType == null) return;
                DeliveryOrderElse.DeliveryType =
                    DeliveryTypes.FirstOrDefault(s => s.DeliveryCode == DeliveryOrderElse.DeliveryType.DeliveryCode);
            }
        }

        public void GetSalesOrderList(Object param)
        {
            if (param == null) return;
            SalesOrderClient.GetSalesOrderListByCostCenterCompleted +=
                SalesOrderClient_GetSalesOrderListByCostCenterCompleted;
            SalesOrderClient.GetSalesOrderListByCostCenterAsync(param as CostCenterDTO);
        }

        private void SalesOrderClient_GetSalesOrderListByCostCenterCompleted(object sender,
                                                                             GetSalesOrderListByCostCenterCompletedEventArgs
                                                                                 e)
        {
            SalesOrderClient.GetSalesOrderListByCostCenterCompleted -=
                SalesOrderClient_GetSalesOrderListByCostCenterCompleted;
            SalesOrders = e.Result;

            if (DeliveryOrderElse != null)
            {
                if (DeliveryOrderElse.SalesOrder == null) return;
                DeliveryOrderElse.SalesOrder =
                    SalesOrders.FirstOrDefault(s => s.SONo == DeliveryOrderElse.SalesOrder.SONo);
            }
        }

        private void GetSPKList()
        {
            spkClient.GetAllSpkCompleted += spkClient_GetAllSpkCompleted;
            spkClient.GetAllSpkAsync();
        }

        private void spkClient_GetAllSpkCompleted(object sender, GetAllSpkCompletedEventArgs e)
        {
            spkClient.GetAllSpkCompleted -= spkClient_GetAllSpkCompleted;
            Spks = e.Result;
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            DeliveryOrderElse = null;
            if (DeliveryOrderElses != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            DeliveryOrderElse = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (DeliveryOrderElses == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();

            if (string.IsNullOrEmpty(DeliveryOrderElse.DONo))
                Errors.Add("Nomor DO tidak boleh kosong");

            foreach (DeliveryOrderElseDetailDTO doDetail in DeliveryOrderElse.DeliveryOrderDetails)
            {
                if (doDetail.Warehouse == null)
                    Errors.Add("NoLog " + doDetail.Inventory.SerialNumber + " Warehousenya belum dipilih!");
            }

            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        public void GetLastNoDeliveryOrderElse()
        {
            client.GetLastDONoCompleted += client_GetLastNoDeliveryOrderElseCompleted;
            client.GetLastDONoAsync();
        }

        private void client_GetLastNoDeliveryOrderElseCompleted(object sender, GetLastDONoCompletedEventArgs e)
        {
            client.GetLastDONoCompleted -= client_GetLastNoDeliveryOrderElseCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);


            DeliveryOrderElse.DONo = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }

        private void AddDeliveryOrderElseDetail()
        {
            DeliveryOrderElse.DeliveryOrderDetails.Add(new DeliveryOrderElseDetailDTO());
        }

        public bool CanLoadSOCommand(Object param)
        {
            return true;
        }

        public void LoadSalesOrder(Object param)
        {
            IsBusy = true;
            if (param == null) return;
            var SO = (SalesOrderDTO) param;
            SalesOrderClient.GetSalesOrderCompleted += SalesOrderClient_GetSalesOrderCompleted;
            SalesOrderClient.GetSalesOrderAsync(SO.SONo);
        }

        private void SalesOrderClient_GetSalesOrderCompleted(object sender, GetSalesOrderCompletedEventArgs e)
        {
            SalesOrderClient.GetSalesOrderCompleted -= SalesOrderClient_GetSalesOrderCompleted;
            DeliveryOrderElse.SalesOrder = e.Result;

            if (e.Result.DeliveryType != null)
                foreach (
                    DeliveryTypeDTO dt in DeliveryTypes.Where(d => d.DeliveryCode == e.Result.DeliveryType.DeliveryCode)
                    )
                    DeliveryOrderElse.DeliveryType = dt;
            DeliveryOrderElse.DeliveryAddress = e.Result.DeliveryAddress;
            DeliveryOrderElse.CustomerName = e.Result.CustomerName;
            DeliveryOrderElse.Address = e.Result.Address;
            DeliveryOrderElse.Telp = e.Result.Telp;

            //Tarik detailnya jika SOnya pake SerialNumber
            DeliveryOrderElse.DeliveryOrderDetails.Clear();
            if (e.Result.Type == "Inventory")
            {
                foreach (SalesOrderDetailDTO sod in e.Result.SalesOrderDetails)
                {
                    var dod = new DeliveryOrderElseDetailDTO
                                  {
                                      Inventory =
                                          sod.Inventory,
                                      QtyPack = sod.Inventory.QtyPack,
                                      QtyUnit = sod.Inventory.QtyUnit,
                                      Panjang = sod.Inventory.Panjang,
                                      Lebar = sod.Inventory.Lebar,
                                      Tinggi = sod.Inventory.Tinggi,
                                      Warehouse = WarehouseSelected
                                  };

                    DeliveryOrderElse.DeliveryOrderDetails.Add(dod);
                }
            }

            IsBusy = false;
        }

        public void LoadSPK(Object param)
        {
            var spk = param as SpkDTO;
            spkClient.GetSpkCompleted += spkClient_GetSpkCompleted;
            spkClient.GetSpkAsync(spk.NoSPK);
        }

        private void spkClient_GetSpkCompleted(object sender, GetSpkCompletedEventArgs e)
        {
            spkClient.GetSpkCompleted -= spkClient_GetSpkCompleted;
            DeliveryOrderElse.SalesOrder = new SalesOrderDTO {SONo = e.Result.NoSPK};

            if (e.Result.DeliveryType != null)
                foreach (
                    DeliveryTypeDTO dt in DeliveryTypes.Where(d => d.DeliveryCode == e.Result.DeliveryType.DeliveryCode)
                    )
                    DeliveryOrderElse.DeliveryType = dt;
            DeliveryOrderElse.DeliveryAddress = e.Result.DeliveryAddress;
            DeliveryOrderElse.CustomerName = e.Result.CustomerName;
            DeliveryOrderElse.Address = e.Result.Address;
            DeliveryOrderElse.Telp = e.Result.Telp;

            //Tarik detailnya jika SOnya pake SerialNumber
            DeliveryOrderElse.DeliveryOrderDetails.Clear();
            if (e.Result.Type == "Inventory")
            {
                foreach (SpkDetailDTO sod in e.Result.SpkDetails)
                {
                    var dod = new DeliveryOrderElseDetailDTO
                                  {
                                      Inventory =
                                          sod.Inventory,
                                      QtyPack = sod.Inventory.QtyPack,
                                      QtyUnit = sod.Inventory.QtyUnit,
                                      Panjang = sod.Inventory.Panjang,
                                      Lebar = sod.Inventory.Lebar,
                                      Tinggi = sod.Inventory.Tinggi,
                                      Warehouse = WarehouseSelected
                                  };

                    DeliveryOrderElse.DeliveryOrderDetails.Add(dod);
                }
            }
        }


        public void Print(Object param)
        {
            Navigation.MyNavigation.Navigate(new Uri("/DeliveryOrderElse/PrintPreviewDO", UriKind.Relative));
            Navigation.Args = param;
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as DeliveryOrderElseDTO, (x as WarehouseDTO).EmailFolder);
            });
        }

        private void client_SendEmailCompleted(object sender, DeliveryOrderElseServices.SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }

        public void GetItemList(Object param)
        {
            ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
            ItemClient.GetItemByNameAsync(param.ToString());
        }

        private void ItemClient_GetItemByNameCompleted(object sender, GetItemByNameCompletedEventArgs e)
        {
            ItemClient.GetItemByNameCompleted -= ItemClient_GetItemByNameCompleted;
            Items = e.Result;
        }

        public void GetSubGrouplist(Object param)
        {
            SubgroupClient.GetSubGroupListByNameCompleted += SubgroupClient_GetSubGroupListByNameCompleted;
            SubgroupClient.GetSubGroupListByNameAsync(param.ToString());
        }

        private void SubgroupClient_GetSubGroupListByNameCompleted(object sender,
                                                                   GetSubGroupListByNameCompletedEventArgs e)
        {
            SubgroupClient.GetSubGroupListByNameCompleted -= SubgroupClient_GetSubGroupListByNameCompleted;
            Subgroups = e.Result;
        }

        public void GetPalletList(Object param)
        {
            PalletClient.GetPalletByWarehouseCompleted += PalletClient_GetPalletByWarehouseCompleted;
            PalletClient.GetPalletByWarehouseAsync(param as WarehouseDTO);
        }

        private void PalletClient_GetPalletByWarehouseCompleted(object sender, GetPalletByWarehouseCompletedEventArgs e)
        {
            PalletClient.GetPalletByWarehouseCompleted -= PalletClient_GetPalletByWarehouseCompleted;
            Pallets = e.Result;
        }

        public void GetQtyOnHand(Object param)
        {
            var doDetail = param as DeliveryOrderElseDetailDTO;
            if (param == null) return;
            InventoryClient.GetQtyOnHandCompleted += InventoryClient_GetQtyOnHandCompleted;
            InventoryClient.GetQtyOnHandAsync(doDetail.Inventory.SerialNumber, doDetail.Warehouse.KodeWarehouse,
                                              doDetail);
        }

        private void InventoryClient_GetQtyOnHandCompleted(object sender, GetQtyOnHandCompletedEventArgs e)
        {
            InventoryClient.GetQtyOnHandCompleted -= InventoryClient_GetQtyOnHandCompleted;
            var doDetail = e.UserState as DeliveryOrderElseDetailDTO;
            if (e.Result.Qty == 0)
                MessageBox.Show("Pilih Gudang yang lain, tidak ada Stok untuk SerialNumber " +
                                doDetail.Inventory.SerialNumber + " di gudang " + doDetail.Warehouse.KodeWarehouse + "!");
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(DeliveryOrderElse.DONo))
            {
                ApplicationService.IsTransactionUsedAsync(DeliveryOrderElse.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = DeliveryOrderElse.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(DeliveryOrderElse.DONo, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = DeliveryOrderElse.DONo;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/DeliveryOrderElse/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(DeliveryOrderElse.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(DeliveryOrderElse.DONo, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }
    }


    public class DeliveryOrderElseWrapViewModel : ViewModelBase
    {
        private readonly InventoryServiceClient InventoryClient;
        private readonly WarehouseServicesClient WarehouseClient;
        private readonly DeliveryOrderElseServicesClient client;
        private DeliveryOrderElseDetailDTO _DeliveryOrderElseDetail;
        private ObservableCollection<InventoryDTO> _Inventorys;
        private ObservableCollection<WarehouseDTO> _warehouses;


        public DeliveryOrderElseWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new DeliveryOrderElseServicesClient();
                InventoryClient = new InventoryServiceClient();
                WarehouseClient = new WarehouseServicesClient();

                AddDetailCommand = new DelegateCommand(AddDeliveryOrderElseDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteDeliveryOrderElseDetail, CanDeleteDetailCommand);
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);
                if (DeliveryOrderElseViewModel.mode == Mode.Add || DeliveryOrderElseViewModel.mode == Mode.Edit)
                {
                    GetWarehouseList();
                    EventAggregator.RegisterMessage("LoadWarehouseCompleted",
                                                    (x) => { LoadWarehouses(DeliveryOrderElseViewModel.DeliveryOrderElse); });
                }
            }
        }

        public DeliveryOrderElseViewModel DeliveryOrderElseViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }


        public ObservableCollection<InventoryDTO> Inventorys
        {
            get { return _Inventorys; }
            private set
            {
                if (Inventorys == value) return;
                _Inventorys = value;
                FirePropertyChanged("Inventorys");
            }
        }


        public DeliveryOrderElseDetailDTO DeliveryOrderElseDetail
        {
            get { return _DeliveryOrderElseDetail; }
            private set
            {
                if (DeliveryOrderElseDetail == value) return;
                _DeliveryOrderElseDetail = value;
                FirePropertyChanged("DeliveryOrderElseDetail");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }

        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }


        private void LoadWarehouses(DeliveryOrderElseDTO DO)
        {
            foreach (DeliveryOrderElseDetailDTO doDetail in DO.DeliveryOrderDetails)
            {
                doDetail.Warehouse = Warehouses.FirstOrDefault(x => x.KodeWarehouse == doDetail.Warehouse.KodeWarehouse);
            }
        }

        public void Edit(Object param)
        {
            DeliveryOrderElseViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/DeliveryOrderElse/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            client.DeleteCompleted += client_DeleteCompleted;
            client.DeleteAsync((DeliveryOrderElseDTO) param);
        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            DeliveryOrderElseViewModel.mode = Mode.Idle;
            var VM = new DeliveryOrderElseViewModel();
        }


        public void GetInventoryList()
        {
            InventoryClient.GetInventoryByCriteriaCompleted +=
                InventoryClient_GetListByCriteriaCompleted;
            InventoryClient.GetInventoryByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void InventoryClient_GetListByCriteriaCompleted(object sender,
                                                                GetInventoryByCriteriaCompletedEventArgs e)
        {
            Inventorys = e.Result;
            if (DeliveryOrderElseViewModel.DeliveryOrderElse != null)
            {
                foreach (
                    DeliveryOrderElseDetailDTO DeliveryOrderElseDetail in
                        DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails)
                {
                    if (DeliveryOrderElseDetail.Inventory == null) continue;
                    DeliveryOrderElseDetail.Inventory =
                        Inventorys.FirstOrDefault(s => s.SerialNumber == DeliveryOrderElseDetail.Inventory.SerialNumber);
                }
            }
        }


        public void GetInventory(Object param)
        {
            DeliveryOrderElseDetail = (DeliveryOrderElseDetailDTO) param;
            if (DeliveryOrderElseDetail.Inventory == null) DeliveryOrderElseDetail.Inventory = new InventoryDTO();
            string SerialNumber = DeliveryOrderElseDetail.Inventory.SerialNumber;
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            InventoryClient.GetInventoryAsync(SerialNumber);
        }

        public void GetInventory2(Object param)
        {
            InventoryClient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            InventoryClient.GetInventoryAsync(param.ToString());
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryClient.GetInventoryCompleted -=
                InventoryClient_GetInventoryCompleted;
            InventoryDTO InventoryTemp = e.Result;
            if (null != InventoryTemp)
            {
                DeliveryOrderElseDetail = new DeliveryOrderElseDetailDTO();
                DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Add(DeliveryOrderElseDetail);
                DeliveryOrderElseDetail.Inventory = InventoryTemp;
                DeliveryOrderElseDetail.QtyPack = InventoryTemp.QtyPack;
                DeliveryOrderElseDetail.Panjang = InventoryTemp.Panjang;
                DeliveryOrderElseDetail.Lebar = InventoryTemp.Lebar;
                DeliveryOrderElseDetail.Tinggi = InventoryTemp.Tinggi;
                DeliveryOrderElseDetail.QtyUnit = InventoryTemp.QtyUnit;
                DeliveryOrderElseDetail.Inventory.Item =
                    e.Result.Item;
                DeliveryOrderElseDetail.Inventory.SatuanUnit =
                    e.Result.SatuanUnit;
                DeliveryOrderElseDetail.Warehouse = DeliveryOrderElseViewModel.WarehouseSelected;
            }
        }

        public void AddDeliveryOrderElseDetail(Object param)
        {
            DeliveryOrderElseDetail = new DeliveryOrderElseDetailDTO();
            DeliveryOrderElseDetail.Inventory = new InventoryDTO();
            DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Add(DeliveryOrderElseDetail);
        }

        public void DeleteDeliveryOrderElseDetail(Object param)
        {
            var DeliveryOrderElseDetail = (DeliveryOrderElseDetailDTO) param;
            if (DeliveryOrderElseDetail == null)
            {
                if (DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Count > 1)
                {
                    if (DeliveryOrderElseDetail.DeliveryOrderDetailId == 0)
                    {
                        DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Remove(DeliveryOrderElseDetail);
                        return;
                    }
                    client.DeleteDetailCompleted += client_DeleteDetailCompleted;
                    client.DeleteDetailAsync(DeliveryOrderElseDetail);
                    DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Remove(DeliveryOrderElseDetail);
                }
            }
            else
            {
                DeliveryOrderElseDetail.DoNo = DeliveryOrderElseViewModel.DeliveryOrderElse.DONo;
                if (DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Count > 1)
                {
                    if (DeliveryOrderElseDetail.DeliveryOrderDetailId == 0)
                    {
                        DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Remove(DeliveryOrderElseDetail);
                        return;
                    }
                    client.DeleteDetailCompleted += client_DeleteDetailCompleted;
                    client.DeleteDetailAsync(DeliveryOrderElseDetail);
                    DeliveryOrderElseViewModel.DeliveryOrderElse.DeliveryOrderDetails.Remove(DeliveryOrderElseDetail);
                }
            }
        }

        private void client_DeleteDetailCompleted(object sender, DeleteDetailCompletedEventArgs e)
        {
            if (e.Result == false) MessageBox.Show("Delete failed!");
        }


        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            DeliveryOrderElseDetail = param as DeliveryOrderElseDetailDTO;
            if (DeliveryOrderElseDetail.Inventory != null)
                if (DeliveryOrderElseDetail.Inventory.SatuanUnit != null)
                    DeliveryOrderElseDetail.QtyUnit = DeliveryOrderElseDetail.QtyPack*
                                                      (DeliveryOrderElseDetail.Panjang*
                                                       DeliveryOrderElseDetail.Lebar*
                                                       DeliveryOrderElseDetail.Tinggi)/
                                                      DeliveryOrderElseDetail.Inventory.SatuanUnit.Pengali;
        }

        public void GetWarehouseList()
        {
            WarehouseClient.GetAllWarehouseCompleted += WarehouseClient_GetAllWarehouseCompleted;
            WarehouseClient.GetAllWarehouseAsync();
        }

        private void WarehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            WarehouseClient.GetAllWarehouseCompleted -= WarehouseClient_GetAllWarehouseCompleted;
            Warehouses = e.Result;
        }
    }


    public class DeliveryOrderElseConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).DONo;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}